package org.example.pglog.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.pglog.mapper.LogMapper;
import org.example.pglog.pojo.BeanDiff;
import org.example.pglog.pojo.FieldDiff;
import org.example.pglog.pojo.Log;
import org.example.pglog.pojo.User;
import org.example.pglog.service.LogService;
import org.example.pglog.util.BeanCompareStringUtil;
import org.example.pglog.util.BeanCompareUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author: 船长
 * @create: 2024-09-01 18:37
 **/

@Service

public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService {
    @Autowired
    private LogMapper logMapper;
    @Override
    public void db(Object oldObj, Object newObj, String[] fields) {
        BeanDiff beanDiff = BeanCompareUtils.compareInclude(oldObj, newObj, fields);
        List<FieldDiff> fieldDiffList = beanDiff.getFieldDiffList();
        for (FieldDiff fieldDiff : fieldDiffList) {
            Log log = new Log();
            log.setId(IdUtil.randomUUID());
            log.setFiledName(fieldDiff.getFieldENName());
            log.setOldValue(fieldDiff.getOldValue().toString());
            log.setNewValue(fieldDiff.getNewValue().toString());
            log.setFiledenName(fieldDiff.getFieldCNName());
            log.setLrsj(new Date());
            logMapper.insert(log);
        }
    }

    @Override
    public void db2(Object oldObj, Object newObj, String[] fields, String[] fieldName) {
        BeanDiff beanDiff = BeanCompareStringUtil.compareInclude(oldObj, newObj, fields, fieldName);
        List<FieldDiff> fieldDiffList = beanDiff.getFieldDiffList();
        for (FieldDiff fieldDiff : fieldDiffList) {
            Log log = new Log();
            log.setId(IdUtil.randomUUID());
            log.setFiledName(fieldDiff.getFieldENName());
            log.setOldValue(fieldDiff.getOldValue().toString());
            log.setNewValue(fieldDiff.getNewValue().toString());
            log.setFiledenName(fieldDiff.getFieldCNName());
            log.setLrsj(new Date());
            log.setOldNr(JSON.toJSONString(oldObj));
            log.setNewNr(JSON.toJSONString(newObj));
            logMapper.insert(log);
        }
    }
}
